package com.cmhk.ding

import java.security.MessageDigest

class DingAuthService {
    def grailsApplication
    def oapiClient

    public String getJsapiTicket(String accessToken) {
        return oapiClient.get(path: "/get_jsapi_ticket", query: [access_token: accessToken]).json?.ticket
    }

    public String getAccessToken() {
        def response = oapiClient.get(path: '/gettoken', query: [corpid    : grailsApplication.config.dingtalk.oapi.corpid,
                                                                 corpsecret: grailsApplication.config.dingtalk.oapi.corpsecret])
        return response.json.access_token
    }

    public String getSign(String nonceStr, long timeStamp, String url) {
        return sign(getAccessToken(), nonceStr, timeStamp, url)
    }


    public String sign(String ticket, String nonceStr, long timeStamp, String url) {
        String plain = "jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${String.valueOf(timeStamp)}&url=${url}"

        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.reset();
        sha1.update(plain.getBytes("UTF-8"));
        return bytesToHex(sha1.digest());

    }

    private static String bytesToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public String getUserInfo(String code) {
        def response = oapiClient.get(path: '/user/getuserinfo', query: [access_token: getAccessToken(), code: code])

        return response.json.userid
    }

}
